import 'package:flutter/material.dart';
import 'package:lib_database/src/network.dart';
import 'package:lib_database/lib_database.dart';

import '../pages/web_page.dart';

class TranUtils {
  static bool isNotEmpty(String? data) {
    return !isEmpty(data);
  }

  static bool isEmpty(String? data) {
    return null == data || data.isEmpty;
  }

  static void goBlockChainScan(BuildContext context, Chain? chain,
      {String? contract, String? address, String? txId, bool replacement = false}) {
    if (null == chain) {
      return;
    }

    String? url = getBlockChainScanUrl(context, chain, contract: contract, address: address, txId: txId);

    if (isNotEmpty(url)) {
      Navigator.of(context).push(MaterialPageRoute(
          builder: (_) {
            return WebPage(url: url!);
          },
          maintainState: false));
    }
  }

  static String? getBlockChainScanUrl(BuildContext context, Chain? chain,
      {String? contract, String? address, String? txId}) {
    if (null == chain) {
      return null;
    }

    if (chain.type == ChainType.eth) {
      if (isNotEmpty(contract) && isNotEmpty(address)) {
        if (chain == ChainList.ompChain) {
          return '${chain.blockExplorerUrl}/address/$address';
        }
        return '${chain.blockExplorerUrl}/token/$contract/?a=$address';
      }

      if (isEmpty(contract) && isNotEmpty(address)) {
        return '${chain.blockExplorerUrl}/address/$address';
      }

      if (isNotEmpty(contract) && isEmpty(address)) {
        return '${chain.blockExplorerUrl}/token/$contract';
      }

      if (isNotEmpty(txId)) {
        return '${chain.blockExplorerUrl}/tx/$txId';
      }
    } else if (chain.type == ChainType.tron) {
      if (isNotEmpty(address)) {
        return '${chain.blockExplorerUrl}/address/$address';
      }

      if (isNotEmpty(contract)) {
        return '${chain.blockExplorerUrl}/contract/$contract';
      }

      if (isNotEmpty(txId)) {
        return '${chain.blockExplorerUrl}/transaction/$txId';
      }
    } else if (chain.isBtcOrBtcTestnet()) {
      if (isNotEmpty(txId)) {
        return '${chain.blockExplorerUrl}/tx/$txId';
      }
    }

    return null;
  }
}
